package com.golddaymicromall.fragment;

import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.salemanager.ConfirmPayActivity;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.adapter.Sale_SecondPurchaseAdapter;
import com.golddaymicromall.bean.ProductInfo;
import com.golddaymicromall.util.ButtonUtils;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by Administrator on 2016/3/4 0004.
 */
public class Sale_SecondPurchaseFragment extends Fragment implements View.OnClickListener {
    private View view;
    private TextView mSecondDiscount;
    private List<ProductInfo> list;
    private List<ProductInfo> listFlag;
    private ListView mLv;
    private float allPrice = 0f;
    private Sale_SecondPurchaseAdapter adapter;
    private String customerid;
    private TextView mAllPrice;
    private TextView mSecond_num;
    private TextView mRealPay;
    private String ids;
    private String count;
    private int num;
    private float PV; //PV
    private float SaleAids; //辅销品价格
    private float RealPay; //实付价
    private float discount;
    private String addressid;
    private String shopGrade;

    //创建观察者
    private DataSetObserver sumObserver = new DataSetObserver() {
        /**
         * 当Adapter的notifyDataSetChanged方法执行时被调用
         */
        @Override
        public void onChanged() {
            super.onChanged();
            //执行相应的操作
            plusPrice();
        }

        /**
         * 当Adapter 调用 notifyDataSetInvalidate方法执行时被调用
         */
        @Override
        public void onInvalidated() {
            super.onInvalidated();
            //执行相应的操作
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_secondpurchase, container, false);
        shopGrade = SPUtils.get(getActivity(), "shop_Grade", "").toString();
        initView();
        attemptShouYitop();
        return view;
    }

    //计算总金额
    public void plusPrice() {
        allPrice = 0f;
        num = 0;
        PV = 0f;
        SaleAids = 0f;
        RealPay = 0f;
        boolean flag = true;
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer sbCount = new StringBuffer();

        switch (shopGrade) {
            case "1":
                discount = (float) 0.6;
                mSecondDiscount.setText("6折");
                break;
            case "2":
                discount = (float) 0.5;
                mSecondDiscount.setText("5折");
                break;
        }
        listFlag = new ArrayList<ProductInfo>();
        for (ProductInfo info : list) {
            if (info.flag) {
                if (!info.getPtid().contains("12")) {
                    PV += (float) (Float.valueOf(info.getPrice()) * info.getCount() * discount);
                    RealPay += (float) (Float.valueOf(info.getPrice()) * info.getCount() * discount);
                    allPrice += (float) (Float.valueOf(info.getPrice()) * info.getCount());
                } else if (info.getPtid().contains("12")) {
                    SaleAids = Float.valueOf(info.getPrice()) * info.getCount();
                    allPrice += SaleAids;
                    RealPay += SaleAids;
                }
                if (info.getCount() != 0) {
                    stringBuffer.append(info.getId() + ",");
                    sbCount.append(info.getCount() + ",");
                }
                num++;
                listFlag.add(info);
            }
            if (sbCount.length() != 0) {
                ids = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
                count = sbCount.toString().substring(0, sbCount.toString().length() - 1);
            }
            if (!info.flag)
                flag = false;
        }

        mAllPrice.setText(String.format("%.2f", allPrice) + "");
        mSecond_num.setText("共 " + num + " 种商品");
        mRealPay.setText("结算（" + String.format("%.2f", RealPay) + ")");
    }

    private void initView() {
        mLv = (ListView) view.findViewById(R.id.secondpurchase_listview);
        mAllPrice = (TextView) view.findViewById(R.id.allPrice);
        mSecond_num = (TextView) view.findViewById(R.id.second_num);
        mRealPay = (TextView) view.findViewById(R.id.shifujia);
        mSecondDiscount = (TextView) view.findViewById(R.id.second_discount);
        mRealPay.setOnClickListener(this);
        getActInfo();
    }

    @Override
    public void onClick(View v) {
        if (ButtonUtils.isFastDoubleClick()) {
            return;
        } else {
            switch (v.getId()) {
                case R.id.shifujia:
                    if (allPrice == 0.0) {
                        Toast.makeText(getActivity(), "请选择购买物品的数量,谢谢", Toast.LENGTH_SHORT).show();
                        return;
                    } else if (RealPay < 2000.0) {
                        Toast.makeText(getActivity(), "二次进货的实付金额不能小于2000", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Intent intent2Confirm = new Intent(getActivity(), ConfirmPayActivity.class);
                    intent2Confirm.putExtra("listFlag", (Serializable) listFlag);
                    startActivity(intent2Confirm);
                    break;
            }
        }


    }

    //获取二次进货数据
    private void attemptShouYitop() {
        //获取本地数据
        customerid = SPUtils.get(getActivity(), "Id", "").toString();
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.order.fristshoping");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("customerid", customerid);
        form.put("orderType", "3");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getActivity(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else {
                            //在这里进行返回值的处理
                            list = new ArrayList<ProductInfo>();
                            list = JSON.parseArray(result, ProductInfo.class);
                            plusPrice();
                            adapter = new Sale_SecondPurchaseAdapter(list, getActivity());
                            adapter.registerDataSetObserver(sumObserver);
                            mLv.setAdapter(adapter);
                        }
                    } else {
                        //在获取不到数据时的处理
                        Toast.makeText(getActivity(), "网络漫游中", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //注销观察者
        if (adapter != null) {
            adapter.unregisterDataSetObserver(sumObserver);
        }
    }


    public void getActInfo() {
        String shopGrade = SPUtils.get(getActivity(), "shop_Grade", "").toString();
        String id = SPUtils.get(getActivity(), "Id", "").toString();
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.order.getactivity");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("shopgrade", shopGrade);
        form.put("ordertype", "3");
        form.put("id", id);
        form.put("ob", "1");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(),RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            SPUtils.put(getContext(), "secondAct", "0");
                            SPUtils.put(getContext(), "secondActPro", "0");
                        } else if ("null".equals(result) || result.contains("[]")) {
                            SPUtils.put(getContext(), "secondAct", "0");
                            SPUtils.put(getContext(), "secondActPro", "0");
                        } else {
                            SPUtils.put(getContext(), "secondAct", result);
                            attemptActProductInfoTask();
                        }
                    } else {
                        Toast.makeText(getContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                },throwable -> {
                    throwable.printStackTrace();
                });
    }
    //活动产品
    public void attemptActProductInfoTask(){
        String shopGrade = SPUtils.get(getActivity(), "shop_Grade", "").toString();
        String id = SPUtils.get(getActivity(), "Id", "").toString();

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.order.getactivity");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("shopgrade", shopGrade);
        form.put("ordertype", "3");
        form.put("id", id);
        form.put("ob", "2");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(),RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result) || result.contains("[]")) {
                            SPUtils.put(getContext(), "secondActPro", "0");
                        } else {
                            SPUtils.put(getContext(), "secondActPro", result);
                        }
                    } else {
                        Toast.makeText(getContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                },throwable -> {
                   throwable.printStackTrace();
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
        attemptShouYitop();
    }
}
